【问题标题】:List of String to List of StatefulWidget Flutter字符串列表到 StatefulWidget Flutter 列表
【发布时间】:2021-09-10 10:03:59
【问题描述】:

我想将此列表字符串转换为列表状态小部件

List<String> listString = [
"HomePage()",
"ProfilePage()"
]

List<StatefulWidget> listStatefulWidget = [];

预期结果:

List<StatefulWidget> listStatefulWidget = [
HomePage(),
ProfilePage()
];

更新: 我需要一个需要 StatefulWidget 列表的导航栏。 tabs 是 StatefulWidget 的列表,应该从 API 获取值。我的 API 返回 listString,所以我需要将其转换为 statefulWidget。

这是我的代码:

var tabs<StatefulWidget> = [
    HomePageView() 
    AccountView(),
  ];

return Scaffold(
    key: scaffoldKey,
    backgroundColor: Theme.of(context).scaffoldBackgroundColor,
    bottomNavigationBar: CurvedNavigationBar(
      key: _bottomNavigationKey,
      index: 0,
      height: 65.0,
      items: [
       //navbar 
      ],
      color: Colors.white,
      buttonBackgroundColor: kSecondaryColor,
      backgroundColor: Colors.transparent,
      animationCurve: Curves.easeInOutQuint,
      animationDuration: Duration(milliseconds: 300),
      onTap: (index) {
        setState(() {
          _page = index;
        });
      },
      letIndexChange: (index) => true,
    ),
    body: tabs[_page]);

}

【问题讨论】:

  • 你想达到什么目的?
  • @NishuthanS 很快我从 API 获得了字符串列表(例如:“HomePage()”)。然后我想将它转换为用于导航到底部导航栏中的每个类的 StatefulWidget

标签: flutter navbar stateful


【解决方案1】:

您无法将 String 转换为 StatefulWidget

您可以使用带有NavigatorState 的字符串导航到应用程序的某些部分。

NavigatorState 的全局键

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

ma​​in.dart

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      navigatorKey: navigatorKey,
      onGenerateRoute: (routeSettings) {
      switch (routeSettings.name) { //add more routes as needed
        case 'Home':
          return MaterialPageRoute(builder: (context) => Home());
        default:
          return MaterialPageRoute(builder: (context) => Profile());
      }
    },
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

导航到页面

您可以使用此navigatorKey.currentState!.pushNamed(&lt;Route Name&gt;) 导航到该页面。

示例:navigatorKey.currentState!.pushNamed('Home') 这会将您导航到 Home 页面。

在您的情况下,您可以从 API 获取路由并构建底部导航栏并使用字符串导航到页面。

例子:

navigatorKey.currentState!.pushNamed(listStatefulWidget [index]);

参考:

https://stackoverflow.com/a/53397266/9074190

https://www.filledstacks.com/post/navigate-without-build-context-in-flutter-using-a-navigation-service/

【讨论】:

  • 感谢@Nisuthan S 先生的回答,不胜感激。我想要的是来自 String coz 导航栏的 listofStatelesWidget 所需的 statefulwidget 列表。我已经更新了我的问题。如果你不介意,你能检查一下吗?谢谢。
猜你喜欢
  • 2021-03-17
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多