gpt4 book ai didi

flutter - 如何将带有数据的数组转换为小部件

转载 作者:行者123 更新时间:2023-12-03 03:56:44 28 4
gpt4 key购买 nike

如何将带有数据的数组转换为小部件

数组

[{id: 1, section_name: Name1, route: Gorod(), icon: Icons.location_city}, {id: 2, section_name: Name2, route: Gorod(), icon: Icons.chat}]

搜索数据
void SearchData() {
info = new List.from(data);
for (int i = 0; i < info.length; i++) {

Widget routed = info[i]['route'];

Navigator.push(context, MaterialPageRoute(builder: (context) => routed));

// Widget test = Gorod();
// Navigator.push(context, MaterialPageRoute(builder: (context) => test));

}
}


出现错误
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type 'String' is not a subtype of type 'Widget'

文件Gorod();
import 'package:flutter/material.dart';

class Gorod extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return GorodState();
}
}

class GorodState extends State<Gorod> {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData (
color: Colors.white,
),
title: Text('Title Gorod', style: TextStyle(color: Colors.white)),
),

body: Container (
child: Text('Text fdsf fds fdsf'),
)
);
}

}


我要去的页面代码

我想从数组中获取路径,然后替换它并转到页面。

最佳答案

从错误中可以看出,您正在从列表中接收字符串。

没有将字符串直接转换为小部件的方法,因此您必须通过比较手动检查从字符串中获取的内容,然后才能从中创建小部件。

希望通过以下简单示例可以使您的想法清晰。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
var info = [
{
'id': 1,
'section_name': 'Name1',
'route': 'Gorod()',
'icon': 'Icons.location_city'
},
{
'id': '2',
'section_name': 'Name2',
'route': 'Gorod()',
'icon': 'Icons.chat'
}
];

List<Widget> searchData() {
List<Widget> _list = [];

for (int i = 0; i < info.length; i++) {
print(info[i]['route']);
if (info[i]['route'] == "Gorod()") {
_list.add(RaisedButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Gorod()));
},
child: Text("text"),
));
}
}

return _list;
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
children: searchData(),
),
),
);
}
}

class Gorod extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return GorodState();
}
}

class GorodState extends State<Gorod> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.white,
),
title: Text('Title Gorod', style: TextStyle(color: Colors.white)),
),
body: Container(
child: Text('Text fdsf fds fdsf'),
));
}
}

关于flutter - 如何将带有数据的数组转换为小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60574994/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com