我创建了一个 Stateful 类,但我不确定如果我添加按钮,setState 命令是否会重新加载屏幕

问题描述 投票:0回答:1

我创建了一个有状态的小部件,我的理解是,如果我在执行期间向类添加实例按钮,我可以使用 setState。我试图根据用户在下拉菜单中选择的内容添加一个按钮,但从未在屏幕上看到该按钮。有人可以告诉我 setState 在哪里来完成这个任务吗?谢谢

 class Page2 extends StatefulWidget {
  const Page2({super.key});
  @override

  _Page2State createState() => _Page2State(); 


}

class _Page2State extends State<Page2> {

  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
            textTheme: TextTheme(
                displayLarge: const TextStyle(
                    fontSize: 84, fontWeight: FontWeight.bold))),
        home: Scaffold(
            body: Center(
                child: Column(children: <Widget>[
          //body: Center(child:
          //body: Column(
          //mainAxisAlignment: MainAxisAlignment.start,
          //crossAxisAlignment: CrossAxisAlignment.start,
          //children: <Widget>[
          //ElevatedButton.icon(
          //  icon: const Icon(Icons.add, size: 18),
          //  label: Text('Create Session'),
          //  onPressed: () {
          //    debugPrint('Create Session Button Pressed');
          //  },
          //),
          //SizedBox(height: 30),
          //ElevatedButton.icon(
          //  icon: const Icon(Icons.add, size: 18),
          //  label: Text('Edit Session'),
          //  onPressed: () {
          //    debugPrint('Edit Session Button Pressed');
          //  },
          //),
          //SizedBox(height: 30),
          //ElevatedButton.icon(
          //  icon: const Icon(Icons.add, size: 18),
          //  label: Text('Delete Session'),
          //  onPressed: () {
          //    debugPrint('Delete Session Button Pressed');
          //  },
          //),
          //Divider(color:Colors.black),
          //Expanded(
          //Flexible(
          //    child: Row(children: <Widget>[
          SizedBox(height: 50),
          //children: [
          DropdownMenu(
              width: 200,
              textStyle: TextStyle(fontSize: 14),
              label: const Text('Session Options'),
              inputDecorationTheme: InputDecorationTheme(
                  isDense: true,
                  contentPadding: const EdgeInsets.symmetric(horizontal: 5),
                  constraints: BoxConstraints.tight(const Size.fromHeight(40)),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  )),
              onSelected: (value) {
                debugPrint(value);
                if (value == 'Create Session') {
                  Set<String> searchType = {'Interior'};
                  SegmentedButton(segments:<ButtonSegment<String>>[ButtonSegment<String>(
                    value:'Interior',label: Text('Interior')),], selected: searchType,);
                }
                setState(() {
                  
                });
              },
              dropdownMenuEntries: <DropdownMenuEntry<String>>[
                DropdownMenuEntry(
                    value: 'Create Session', label: 'Create Session'),
                DropdownMenuEntry(value: 'Edit Session', label: 'Edit Session'),
                DropdownMenuEntry(
                    value: 'Delete Session', label: 'Delete Session'),
              ]
            ),
          ]
        )
      )
    )
  );
  }
}
flutter
1个回答
0
投票

您的

StatefulWidget
需要一个代表小部件状态的变量。在下面的示例中,这是字符串
sessionState
。请注意,
button
中定义的小部件
build
取决于
sessionState
,而
sessionState
是在
onSelected
DropDownMenu
回调中设置的。

在小部件状态更改后,调用方法

setState
来重建您的小部件。您可以将下面的示例复制/粘贴到 飞镖盘.

import 'package:flutter/material.dart';

class Page2 extends StatefulWidget {
  const Page2({super.key});
  @override
  _Page2State createState() => _Page2State();
}

class _Page2State extends State<Page2> {
  String sessionState =
      'none'; // The variable describing the state of the widget

  Widget build(BuildContext context) {
    final button = switch (sessionState) {
      'Create Session' => SegmentedButton(segments: <ButtonSegment<String>>[
          ButtonSegment<String>(value: 'Interior', label: Text('Interior')),
        ], selected: {
          'Interior'
        }),
      _ => SizedBox(), // A placeholder
    };

    return MaterialApp(
        theme: ThemeData(
            textTheme: TextTheme(
                displayLarge: const TextStyle(
                    fontSize: 84, fontWeight: FontWeight.bold))),
        home: Scaffold(
            body: Center(
                child: Column(
          children: <Widget>[
            SizedBox(height: 50),
            //children: [
            DropdownMenu(
              width: 200,
              textStyle: TextStyle(fontSize: 14),
              label: const Text('Session Options'),
              inputDecorationTheme: InputDecorationTheme(
                  isDense: true,
                  contentPadding: const EdgeInsets.symmetric(horizontal: 5),
                  constraints: BoxConstraints.tight(const Size.fromHeight(40)),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  )),
              onSelected: (value) {
                debugPrint(value);
                if (value != null) {
                  setState(() {
                    // Triggering a rebuild of your widget
                    sessionState = value; // Setting the state variable
                  });
                }
              },
              dropdownMenuEntries: <DropdownMenuEntry<String>>[
                DropdownMenuEntry(
                    value: 'Create Session', label: 'Create Session'),
                DropdownMenuEntry(value: 'Edit Session', label: 'Edit Session'),
                DropdownMenuEntry(
                    value: 'Delete Session', label: 'Delete Session'),
              ],
            ),
            button,
          ],
        ))));
  }
}

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

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

  @override
  Widget build(BuildContext context) => Page2();
}

© www.soinside.com 2019 - 2024. All rights reserved.