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
],
)
Related
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)]
When i create a list, i can only use it in the class where i created the list. But in another class i get an error 'undefined name' when i want to use the list. How can i get access to the list?
For example in my code i created a list 'plans' with strings.
class _PlanOverviewState extends State<PlanOverview> {
List<String> plans = ['Plan A', 'Plan B'];
void addPlan(String neuerPlan) {
setState(() {
plans.add(neuerPlan);
});
Navigator.of(context).pop();
}
Now I want to output a single string from the list plans in another Widget in the Appbar as title, so the User know where he is.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(plans[i]))
How can i get access to the list plans?
One option is to create & use an InheritedWidget-style accessor for your State class and then you can access it from any descendant context.
import 'package:flutter/material.dart';
class InheritedWidgetPage extends StatefulWidget {
#override
_InheritedWidgetPageState createState() => _InheritedWidgetPageState();
static _InheritedWidgetPageState of(BuildContext context) =>
context.findAncestorStateOfType<_InheritedWidgetPageState>();
}
class _InheritedWidgetPageState extends State<InheritedWidgetPage> {
List<String> plans = ['Plan A', 'Plan B'];
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
_InheritedWidgetPageState _state = InheritedWidgetPage.of(context);
return Scaffold(
appBar: AppBar(
title: Text(_state.plans[0]),
),
body: Center(
child: ElevatedButton(
child: Text('Goto ${_state.plans[1]}'),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (context) => PlanPage(1))),
),
),
);
}
}
class PlanPage extends StatelessWidget {
final int index;
PlanPage(this.index);
#override
Widget build(BuildContext context) {
_InheritedWidgetPageState _state = InheritedWidgetPage.of(context);
return Scaffold(
appBar: AppBar(
title: Text(_state.plans[index]),
),
body: Center(
child: Text('You are here: ${_state.plans[index]}'),
),
);
}
}
This can be pretty confusing to understand at first, but will make more sense as you get more familiar with Flutter's declarative framework.
For the above example to work, you need to have a MaterialApp ancestor widget, and your State class (where you're holding your plans state object) needs to be its parent. I explain why on a similar question here.
Your other option is to use a State Management package of which there are lots, which can help you simplify access to state objects.
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 have a registration form in my application and I want to check if the DropDown value is empty or not. So I will give a warning to the screen. But I couldn't use DropDown value on checkFieldStatus function. How can I get this?
These are my codes that i used for my app:
class Register extends StatefulWidget {
#override
_RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
List listGender = ["Erkek", "Kız"];
List listTeacher = ["Oğulcan Baybars", "Kübra Yeşilkazak"];
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String genderHolder;
String teacherHolder;
var _imageFile = null;
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: [
CustomDropDownField(
list: listGender,
hintText: "Cinsiyet",
value: genderHolder,
),
CustomDropDownField(
list: listTeacher,
hintText: "Öğretmeniniz",
value: teacherHolder,
),
ElevatedButton(
onPressed: () {
checkFieldStatus();
},
child: Text("Kayıt Ol")),
],
),
),
);
}
Future<void> checkFieldStatus() async {
if (_imageFile != null) {
showDialog(
context: context,
builder: (context) {
return ErrorAlertDialog(
message: "Resim yüklendi",
);
});
} else {
**Where I want to do the checks**
? registerUser()
: displayDialog("Lütfen formdaki bütün alanları doldurun.";
}
}
}
My CustomDropDownField like this:
import 'package:flutter/material.dart';
class CustomDropDownField extends StatefulWidget {
final List list;
final String hintText;
String value;
CustomDropDownField({
Key key,
this.list,
this.hintText,
this.value,
}) : super(key: key);
#override
_CustomDropDownFieldState createState() => _CustomDropDownFieldState();
}
class _CustomDropDownFieldState extends State<CustomDropDownField> {
#override
Widget build(BuildContext context) {
return Container(
child: DropdownButton(
isExpanded: true,
hint: Text(widget.hintText),
items: widget.list.map((valueItem) {
return DropdownMenuItem(value: valueItem, child: Text(valueItem));
}).toList(),
value: widget.value,
onChanged: (newValue) {
setState(() {
widget.value = newValue;
});}),);}
CustomDropDownField only changes the String value in its own state it does not reflect to the _RegisterState screen you can do a few different things:
Pass a callback function that updates the value in the _RegisterState screen
or even better
Use a state management like Provider or Bloc to update the value.
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
]
),