FluttersetState()在列表内不起作用< Widget>

hof1towb  于 2023-03-04  发布在  Flutter
关注(0)|答案(1)|浏览(125)

我有这个代码:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: App(),
    );
  }
}

class App extends StatefulWidget {
  const App({super.key});

  @override
  State<App> createState() => _AppState();
}

class _AppState extends State<App> {
  int navBarIndex = 0;

  void navBarTap(int index) {
    setState(() {
      navBarIndex = index;
    });
  }

  double lengthSliderValue = 20;

  late List<Widget> pages = <Widget>[
    /* Page 1 */ Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.stretch,
  
      children: <Widget>[
        /* Slider */ Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(" Length", style: TextStyle(fontSize: 18)),
            Slider(
              value: lengthSliderValue,
              min: 1,
              max: 30,
              divisions: 29,
              label: lengthSliderValue.round().toString(),
              onChanged: (double value) {
                setState(() {
                  lengthSliderValue = value;
                });
              },
            ),
          ],
        ),
      ],
    ),
    /* Page 2 */ Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.stretch,

      children: const <Widget>[
        // Just some test widgets
        Icon(Icons.check_circle_outline_rounded, size: 80),
        Icon(Icons.check_circle_rounded, size: 80)
      ]
    )
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Test App",
      
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Test App"),
          centerTitle: true,
        ),

        bottomNavigationBar: BottomNavigationBar(
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.get_app_rounded),
              label: "Page 1",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.check_circle_outline_rounded),
              label: "Page 2",
            ),
          ],
          currentIndex: navBarIndex,
          onTap: navBarTap,
        ),

        body: pages[navBarIndex]
      ),
    );
  }
}

显然这不是全部代码,我已经删除了所有与问题无关的不必要的东西。
我将print(lengthSliderValue);放入滑块setState中,值发生了变化,问题是滑块在视觉上没有变化。
我是dart/flutter的新手,我来自于C#和Python。也许我在这方面做错了,不应该使用late?也许有一个更好的方法来使用带有导航栏的页面?
先谢了。

vuktfyat

vuktfyat1#

您正在创建pages变量,而它第一次只分配一个,并且会中断当前上下文链。如果您想在内部更新项目,您可以使用页面内的有状态小部件,或者当前您可以使用方法

List<Widget> pages() => <Widget>[

打电话

body: pages()[navBarIndex]),

相关问题