颤动-使用道具数据创建下拉按钮

时间:2020-11-09 20:03:20

标签: flutter dart mobile flutter-provider

我正在学习颤抖一段时间,但有一个我不知道如何解决的问题。 我正在尝试使用从父母那里传递来的数据创建一个下拉按钮,该数据是[[work],'hobby','social']等单词的列表。

我的问题是更改值后的下拉按钮仍显示初始按钮,我认为问题出在我初始化“ dropdownValue”时,因为我在构建方法中执行此操作,但无法从外部访问属性该小部件。

class TaskSheet extends StatefulWidget {
  @override
  _TaskSheetState createState() => _TaskSheetState();
  final List categories;
  TaskSheet(this.categories);
**// HERE I RECIVE THE LIST** 
}

class _TaskSheetState extends State<TaskSheet> {
  String dropdownValue;
  // I CANT ASSIGN VALUE HERE BECAUSE USING widget.categories  DONT WORK HERE AND IT MUST BE INSIDE BUILD METHOD
  @override
  Widget build(BuildContext context) {
    var categoriesList = widget.categories
        .map(
          (category) => DropdownMenuItem(
            value: category.title,
            child: Text(category.title),
          ),
        )
        .toList();
    dropdownValue = categoriesList[0].value; // THIS VALUE ALWAYS STAY THE SAME 

    return BottomSheet(
      builder: (context) => Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 30.0, vertical: 16),
        child: Column(
          children: [
            Text('Add new task'),
            TextField(
              decoration: InputDecoration(labelText: 'What you wanna do?'),
            ),
            DropdownButton(
              icon: Icon(Icons.keyboard_arrow_down),
              focusColor: Theme.of(context).primaryColor,
              value: dropdownValue,
              onChanged: (newValue) {
                setState(() {
                  dropdownValue = newValue; // THIS HAVE NO IMPACT ON INITAL VALUE
                });
              },
              items: categoriesList,
            ),
          ],
        ),
      ),
      onClosing: () {},
    );
  }
}

我认为,如果我能从构建方法的替代方法中获取widget.props的方法,它将起作用,但我不知道该怎么做

1 个答案:

答案 0 :(得分:1)

您可以在下面复制粘贴运行完整代码
您可以在下面查看工作演示
步骤1:Category extends Equatable

import 'package:equatable/equatable.dart';

class Category extends Equatable {
  String title;
  Category({this.title});

  @override
  List<Object> get props => [title];
}

步骤2:dropdownValueCategory而不是String,并使用initState()

  Category dropdownValue;

  @override
  void initState() {
    dropdownValue = widget.categories[0];
    super.initState();
  }

第3步:valuecategory

DropdownMenuItem<Category>(
            value: category,

工作演示

enter image description here

完整代码

import 'package:flutter/material.dart';
import 'package:equatable/equatable.dart';

class Category extends Equatable {
  String title;
  Category({this.title});

  @override
  List<Object> get props => [title];
}

class TaskSheet extends StatefulWidget {
  @override
  _TaskSheetState createState() => _TaskSheetState();
  final List<Category> categories;
  TaskSheet(this.categories);
}

class _TaskSheetState extends State<TaskSheet> {
  Category dropdownValue;

  @override
  void initState() {
    dropdownValue = widget.categories[0];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var categoriesList = widget.categories
        .map(
          (category) => DropdownMenuItem<Category>(
            value: category,
            child: Text(category.title),
          ),
        )
        .toList();

    return BottomSheet(
      builder: (context) => Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 30.0, vertical: 16),
        child: Column(
          children: [
            Text('Add new task'),
            TextField(
              decoration: InputDecoration(labelText: 'What you wanna do?'),
            ),
            DropdownButton<Category>(
              icon: Icon(Icons.keyboard_arrow_down),
              focusColor: Theme.of(context).primaryColor,
              value: dropdownValue,
              onChanged: (newValue) {
                setState(() {
                  dropdownValue =
                      newValue; // THIS HAVE NO IMPACT ON INITAL VALUE
                });
                print(dropdownValue.title);
              },
              items: categoriesList,
            ),
          ],
        ),
      ),
      onClosing: () {},
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TaskSheet([
              Category(title: "work"),
              Category(title: "hobby"),
              Category(title: "social")
            ]),
          ],
        ),
      ),
    );
  }
}