im new to dart/flutter, im trying to make a textfield that user can input index value and a button to submit it. For example, if user input 1 and click submit , then it will print apple. Thank you for helping. The error i get is String can't be assigned to a int, can i know how to fix this. Thank you.
Here is my source code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Fruity App'),
),
body: MyWidget(),
),
);
}
}
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
String _textString = 'Enter input to select your favourite fruit';
String _select =
'1 = Apple \n 2 = Pineapple \n 3 = Potato \n 4 = Orange \n 5 = Tomato';
var fruitsIndex = 0;
List<String> fruits = ['Apple', 'Pineapple', 'Potato', 'Orange', 'Tomato'];
TextEditingController a = new TextEditingController();
#override
Widget build(BuildContext context) {
return Column(
children: [
TextField(controller: a),
Text(
_textString,
style: TextStyle(fontSize: 25),
),
Text(
_select,
style: TextStyle(fontSize: 25),
),
RaisedButton(child: Text('Submit'), onPressed: buttonPressed),
],
);
}
void buttonPressed() {
print(fruits[a.text.toString()]);
}
}
Try parsing that user input to int.
fruits[int.parse(a.text)]
Related
I'm trying to set quotes from list to Text widget but i am facing this problem
The argument type 'List<Iterable>' can't be assigned to the parameter type 'List'.
this is my code
import 'package:flutter/material.dart';
void main() {
runApp(myApp());
}
class myApp extends StatefulWidget {
#override
_myAppState createState() => _myAppState();
}
class _myAppState extends State<myApp> {
List<String> quotesList = [
"The secret of getting ahead is getting started",
"Only the paranoid survive",
"It’s hard to beat a person who never gives up.",
"Never Had luck never needed it"
];
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.black38,
title: Text("Quotes"),
),
body: Column(
children: [quotesList.map((e) => Text(e))].toList(),
),
),
);
}
}
You don't need to wrap the list with '[' and ']'
Column(
children: quotesList.map((e) => Text(e)).toList(),
),
And if you want to add more widgets, you can use like this
Column(
children: quotesList.map<Widget>((e) => Text(e)).toList()
..addAll([
Container() //You can use addAll method and add some juicy widgets
]),
),
Here is another (easy) approach.
Add this function to your current class -
List<Widget> getTextWidgets() {
List<Widget> _widgets = [];
for(int i=0;i<quotesList.length;i++) {
_widgets.add(
Text(quotesList[i])
);
}
return _widgets;
}
And simply call it like -
body: Column(
children: getTextWidgets(),
),
Remove [] from the quotesList -
quotesList.map((e) => Text(e)).toList(),
This might fix your issue -
import 'package:flutter/material.dart';
void main() {
runApp(myApp());
}
class myApp extends StatefulWidget {
#override
_myAppState createState() => _myAppState();
}
class _myAppState extends State<myApp> {
List<String> quotesList = [
"The secret of getting ahead is getting started",
"Only the paranoid survive",
"It’s hard to beat a person who never gives up.",
"Never Had luck never needed it"
];
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.black38,
title: Text("Quotes"),
),
body: Column(
children: quotesList.map((e) => Text(e)).toList(),
),
),
);
}
}
To answer your question, you need to remove the [ and ], to look like this
quotesList.map((e) => Text(e)).toList()
If you want to add more widgets, you can use the spread operator
Column(
children: <Widget>[
// you can add more widgets here
...quotesList.map((e) => Text(e)),
// you can add more widgets here too
],
)
I have 2 separate files in my Flutter application, main.dart and class1.dart
class1.dart is defined in my models/ folder
I am trying to access the List that I created from the SampleWidget class but I am unsure how to do this. IntelliSense wasn't able to find the List I had made from the instance object of SampleWidget.
What I'm trying to achieve is:
AssetImage(SampleWidget.listSampleWidget[0].foo)
class1.dart
class SampleWidget {
final String foo;
final int bar;
SampleWidget({this.foo, this.bar});
}
List<SampleWidget> listSampleWidget = [
SampleWidget(
foo: 'assets/001.png',
bar: 420,
),
];
main.dart is just the default boilerplate code when creating a new Flutter application,
main.dart
import 'package:flutter/material.dart';
import 'package:sandbox1/models/class1.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final extSampleClass = SampleWidget();
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
//AssetImage(<pass SampleWidget foo parameter from the List here>),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
How do I reference to the List from the class here? Is something like this even doable or is there a different approach?
AssetImage() cannot be used as a standalone widget. Using Image.asset() worked. I can call the List object directly without having to reference the class apparently.
So the code will look something like:
Image.asset(listSampleWidget[0].foo)
And I got the picture on my test device!
I want to create a list, those people location = "Barishal". That's why, I created a function and try to push data ( which data I obtained from getSpecific() function ) to a new list ( myList ). But It created a problem ....
here is my code-
class BookData extends ChangeNotifier {
List<MyModel> data = [
MyModel(name: "Abir", location: "Dhaka"),
MyModel(name: "Shuvro", location: "Barishal"),
MyModel(name: "Anik", location: "Barishal")
];
List<MyModel> get getMydata{
return data;
}
getSpecific (){
for(int i=0;i<data.length;i++){
if(data[i].location=="Barishal"){
print(data[i]);
return data[i];
}
}
}
List myList = getSpecific();
}
How can I fix this problem ?
You can copy paste run full code below
You can provide search string and use UnmodifiableListView<MyModel> and filter with _myData.where
code snippet
class BookData extends ChangeNotifier {
final List<MyModel> _myData = [
MyModel(name: "Abir", location: "Dhaka"),
MyModel(name: "Shuvro", location: "Barishal"),
MyModel(name: "Anik", location: "Barishal")
];
String _searchString = "";
UnmodifiableListView<MyModel> get books => _searchString.isEmpty
? UnmodifiableListView(_myData)
: UnmodifiableListView(
_myData.where((dog) => dog.location.contains(_searchString)));
void getSpecific(String searchString) {
_searchString = searchString;
print(_searchString);
notifyListeners();
}
}
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:collection';
import 'package:provider/provider.dart';
class BookData extends ChangeNotifier {
final List<MyModel> _myData = [
MyModel(name: "Abir", location: "Dhaka"),
MyModel(name: "Shuvro", location: "Barishal"),
MyModel(name: "Anik", location: "Barishal")
];
String _searchString = "";
UnmodifiableListView<MyModel> get books => _searchString.isEmpty
? UnmodifiableListView(_myData)
: UnmodifiableListView(
_myData.where((dog) => dog.location.contains(_searchString)));
void getSpecific(String searchString) {
_searchString = searchString;
print(_searchString);
notifyListeners();
}
}
class MyModel {
final String name;
final String location;
MyModel({this.name, this.location});
}
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => BookData(),
child: MyApp(),
),
);
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _controller = TextEditingController();
String _searchText;
#override
void initState() {
_controller.addListener(
() {
setState(() {
_searchText = _controller.text;
});
},
);
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Example',
home: Scaffold(
appBar: AppBar(
title: Text('Example'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
TextField(
controller: _controller,
decoration: InputDecoration(
hintText: "Search",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(4.0),
),
),
),
onChanged: (value) {
Provider.of<BookData>(context, listen: false)
.getSpecific(value);
},
),
Consumer<BookData>(builder: (context, bookData, child) {
print(bookData.books.toString());
return Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: bookData.books.length,
itemBuilder: (context, index) => Card(
elevation: 3,
child: ListTile(
title: Text(bookData.books[index].name),
),
)),
);
}),
],
),
),
);
}
}
When you need to filter a list, you can use the where method.
Here's a simple example.
List<MyModel> myNewList = data.where((item) => item.location == "Barishal").toList();
Anyway, your code seems to be returning just the first item, not a list.
I fixed your code like below
List<MyModel> getSpecific (){
List<MyModel> result = [];
for(int i=0;i<data.length;i++){
if(data[i].location=="Barishal"){
print(data[i]);
result.add(data[i]);
}
}
return result;
}
I am trying to list categories of products in my app, and i am using provider package for state management. During the build time its shows the list is empty even though it is not, then I add a click event to update the list that time it works.
I call the getAllCategories() function during the splash screen and the vallCategoryList has values.
This is my category class
class Category with ChangeNotifier{
int catId;
String catName;
String catThumbnail;
List<SetCategory> allCategoryList = [];
void getAllCategories() async {
String categoryUrl = 'https://app.ecwid.com/api/ccccccc';
Response allCategory = await get(categoryUrl);
print('getAllCategories');
if (allCategory.statusCode == 200) {
var categoryData = allCategory.body;
int totalcount = jsonDecode(categoryData)['count'];
if (allCategoryList.length != totalcount) {
allCategoryList.clear();
for (int i = 0; i < totalcount; i++) {
allCategoryList.add(SetCategory(
catId: jsonDecode(categoryData)['items'][i]['id'],
catName: jsonDecode(categoryData)['items'][i]['name'],
catThumbnail: jsonDecode(categoryData)['items'][i]['thumbnailUrl'],
));
}
}
}
print('allcategorylist length ${allCategoryList.length}');
notifyListeners();
}
}
class SetCategory {
int catId;
String catName;
String catThumbnail;
SetCategory(
{ this.catId, this.catName, this.catThumbnail});
}
My code for screen
class HomeScreen extends StatefulWidget {
static const String id = 'homeScreen';
// static int reload = 0;
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
final category = Provider.of<Category>(context);
print('category length ${category.allCategoryList.length}'); // here it shows length as 0 even though it has a value of 16.
return Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Category ${category.allCategoryList.length}',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15.0,
),
textAlign: TextAlign.start,
),
),
InkWell(
onTap: () {
category.getAllCategories(); // when i tap here this updates the list
}),
],
),
Did you use ChangeNotifierProvider in your Widget as shown here
If you just used Provider it is not updating but just makes the object accessible from the descendants
Solved by adding a Consumer, changed code like this
child: Consumer<Category>(
builder: (_,category,__){
return ListView.builder();
}
I am using Firebase realtime database to retrieve information and then present it in a scrollable DataTable.
To make the DataTable scrollable, I wrapped it up in a ListView, as per the comment of this post:
DataTable - make scrollable, set background colour and fix/freeze header row and first column
This is my code:
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'cprdata.dart';
import 'dart:convert';
class CprAnalysis extends StatefulWidget {
#override
CPRState createState() => CPRState();
}
class CPRState extends State<CprAnalysis> {
///var cpr = UpdateData.getData();
List<FilterData> acData;
List<FilterData> getData() {
var cpr = <FilterData>[];
DatabaseReference cprData = FirebaseDatabase.instance.reference();
cprData.reference().once().then((DataSnapshot snap) {
var d = snap.value;
final jsonE = json.encode(d);
final jsonResponse = json.decode(jsonE);
MyDataList zz = new MyDataList.fromJson(jsonResponse);
zz.myList.forEach((data) {
cpr.add(FilterData(sYMBOL: data.SYMBOL, fORECAST: data.FORECAST));
}
);
},
);
print(cpr);
return cpr;
}
#override
void initState() {
super.initState();
acData = getData();
}
Widget bodydata() => Expanded(
child: ListView(
///shrinkWrap: true,
padding: const EdgeInsets.all(8.0),
childern: <Widget>[
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
columns: <DataColumn>[
DataColumn(
label: Text("Symbol"),
numeric: false,
),
DataColumn(
label: Text("Forecast"),
numeric: false,
),
],
rows: acData.map((data) =>
DataRow(
cells: [
DataCell(
Text(data.sYMBOL),
showEditIcon: false,
placeholder: false,
),
DataCell(
Text(data.fORECAST),
showEditIcon: false,
placeholder: false,
)
],
),
)
.toList()
),
),
]
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("CPR Analysis"),
),
body: Container(
child: bodydata(),
),
);
}
}
class FilterData {
String sYMBOL, fORECAST;
FilterData({
this.sYMBOL,
this.fORECAST});
}
Expected output: Scrollable DataTable.
Actual output: error: The named parameter 'childern' isn't defined under ListView()
You misspelled children as childern in your code.
Make your ListView code as -
ListView(
children: <Widget> [
//Your remaining code
]
),