当前完整的代码允许我将值添加到Grid中的第一项。如何将表单中的值添加到GridView上的所有其他项。
我尝试将Container封装在for循环中,就像这样,希望它可以迭代每个其他项并将其值添加到文本字段中。但它不起作用。
return list.map((String string) {
for (int i = 0; i < listDates.length; i = i + 2) {
return list.indexOf(string) == i
}
这是完整的代码供您参考
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: TextInputValue(),
);
}
}
class TextInputValue extends StatefulWidget {
@override
_TextInputValueState createState() => _TextInputValueState();
}
class _TextInputValueState extends State<TextInputValue> {
final _textInputController = TextEditingController();
String showText = " ";
_TextInputValueState({this.showText});
_onPressed() {
setState(() {
showText = _textInputController.text;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Text Input Value'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Expanded(
child: GridView.count(
crossAxisCount: 4,
children: getBox(showText),
),
),
Text("Submitted Text: $showText"),
Padding(
padding: const EdgeInsets.all(15.0),
child: TextFormField(
controller: _textInputController,
decoration: InputDecoration(hintText: 'Enter a Text here'),
),
),
RaisedButton(
onPressed: _onPressed,
child: Text('Submit'),
),
SizedBox(
height: 300.0,
),
],
),
));
}
}
List<Widget> getBox(var data) {
var list = ['a', '2', '3', '4', '5', '6', '7', '8', '9'];
return list.map((String string) {
return list.indexOf(string) == 0
? Container(
margin: const EdgeInsets.all(2.0),
padding: const EdgeInsets.all(5.0),
decoration: myBoxDecoration(),
child: Text(data),
)
: Container(
margin: const EdgeInsets.all(2.0),
padding: const EdgeInsets.all(5.0),
decoration: myBoxDecoration(),
);
}).toList();
}
BoxDecoration myBoxDecoration() {
return BoxDecoration(
border: Border.all(width: .1),
);
}
答案 0 :(得分:2)
将整个getBox
替换为:
List<Widget> getBox(String data) => List<Widget>.generate(
9,
(int i) => i % 2 == 0
? Container(
margin: const EdgeInsets.all(2.0),
padding: const EdgeInsets.all(5.0),
decoration: myBoxDecoration(),
child: Text(data),
)
: Container(
margin: const EdgeInsets.all(2.0),
padding: const EdgeInsets.all(5.0),
decoration: myBoxDecoration(),
),
);
或更简短地说:
List<Widget> getBox(String data) => List<Widget>.generate(
9,
(int i) => Container(
margin: const EdgeInsets.all(2.0),
padding: const EdgeInsets.all(5.0),
decoration: myBoxDecoration(),
child: i % 2 == 0 ? Text(data) : null,
),
);