Riverpod 消费者小部件 - 如何从下拉小部件观看

时间:2021-08-02 00:48:02

标签: flutter consumer riverpod

尝试使用 riverpod,没有找到答案 - 在线示例使用相同的 dart 文件。

我想传递在位于不同文件的下拉列表中选择的公司名称。 这里的代码应该是什么:

SELECT COALESCE(t2.user_id,t1.user_id) AS user_id,
      t1.signupdate
FROM Table_1 AS t1 LEFT JOIN Table_2 AS t2 
ON t1.user_id = t2.user_id_request
WHERE CASE 
           WHEN t2.user_id='16'/*($_SESSION[ 'SESS_USER_ID' ])*/ 
                   AND friend_status IN (0,1) THEN 0
           WHEN t1.user_id='16'/*($_SESSION[ 'SESS_USER_ID' ])*/ THEN 0
           ELSE 1 END=1;

所以我可以在这里获取值:

DropdownButton<String>(
          items: CompanyList.map((value) {
            return DropdownMenuItem<String>(
              child: Text(
                value,
                style: TextStyle(color: lightGrey),
              ),
              value: value,
            );
          }).toList(),
          value: company,
          onChanged: (value) {
            setState(() {
              company= value; // service 
            });
            ** final compamyProvider = Provider((_) => value); **
          },
        ),

1 个答案:

答案 0 :(得分:0)

创建一个 StateProvider

final dropItemProvider = StateProvider<String>((ref) => "");

完整代码:


class MainWidgetR extends StatefulWidget {
  @override
  _MainWidgetState createState() => _MainWidgetState();
}

class _MainWidgetState extends State<MainWidgetR> {
  String value = "Company 0";

  final items = List.generate(
    4,
    (index) => DropdownMenuItem(
      child: Text("Company $index"),
      value: "Company $index",
    ),
  );

  @override
  void initState() {
    super.initState();

    ///setting default value  on provider
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      context.read(dropItemProvider).state = items[0].value!;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            DropdownButton(
              items: items,
              value: value,
              onChanged: (value) {
                context.read(dropItemProvider).state = value as String;
                setState(() {
                  value = value;
                });
              },
            ),
            RiverPodRespone(),
          ],
        ),
      ),
    );
  }
}

class RiverPodRespone extends ConsumerWidget {
  const RiverPodRespone({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, watch) {
    final dataNotifier = watch(dropItemProvider);
    return Container(
      child: Text("${dataNotifier.state}"),
    );
  }
}

有帮助吗?