提供程序在Flutter中

huangapple go评论129阅读模式
英文:

Providers in flutter

问题

我正在构建一个包含标题和描述详细信息的笔记应用,其中我的输入来自于弹出的AlertDialog中的TextField。不幸的是,屏幕是空白的。

这是我的UserNotes类:

class UserNotes {
  String? title;
  String? description;

  UserNotes({required this.title, required this.description});
}

这是我的Provider:

import 'package:notes_update/models/UserMethods.dart';
import 'package:notes_update/models/UserNotes.dart';
import 'package:flutter/foundation.dart';
import 'package:provider/provider.dart';

class ProviderData extends ChangeNotifier {
  List<UserNotes> _users = [];

  List<UserNotes> get newusers => _users;

  IncomingData() {
    _users = GettingNotes().addDetails();
    notifyListeners();
  }
}

这个类返回一个UserNotes列表。

import 'UserNotes.dart';

class GettingNotes {
  String? newtitle;
  String? description;
  List<UserNotes> addDetails() {
    List<UserNotes> details = [];
    if (details.isEmpty) {
      details.add(UserNotes(title: newtitle!, description: description!));
    }

    return details;
  }
}

这是我的UI:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:notes_update/models/UserMethods.dart';
import 'package:notes_update/models/UserNotes.dart';
import 'package:provider/provider.dart';

import '../Provider/Provder.dart';

class Notes extends StatefulWidget {
  createState() => _Notes();
}

class _Notes extends State<Notes> {
  var title;
  var description;

  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Consumer<ProviderData>(builder:
              (BuildContext context, ProviderData value, Widget? child) {
            return ListView.builder(
                itemCount: value.newusers.length,
                itemBuilder: ((context, index) {
                  return ListTile(
                    title: Text(value.newusers[index].title!),
                    leading: Text(value.newusers[index].description!),
                  );
                }));
          }),
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              FloatingActionButton(
                backgroundColor: Colors.black54,
                child: Center(
                  child: Icon(
                    Icons.add,
                    size: 40,
                  ),
                ),
                onPressed: () => showDialog(
                    context: context,
                    builder: (BuildContext context) => AlertDialog(
                            title: Text('NOTES INFO'),
                            content: Column(
                              children: [
                                TextFormField(
                                  decoration: InputDecoration(
                                      hintText: 'Enter notes title',
                                      border: OutlineInputBorder()),
                                  onChanged: (value) {
                                    setState(() {
                                      title = value;
                                    });
                                  },
                                ),
                                SizedBox(height: 50),
                                TextFormField(
                                  decoration: InputDecoration(
                                      hintText: 'Enter notes description',
                                      border: OutlineInputBorder()),
                                  onChanged: (value) {
                                    setState(() {
                                      description = value;
                                    });
                                  },
                                ),
                              ],
                            ),
                            actions: <Widget>[
                              TextButton(
                                onPressed: () {
                                  setState(() {
                                    GettingNotes().newtitle = title;
                                    GettingNotes().description = description;
                                  });
                                  Navigator.pop(context);
                                },
                                child: Text('Save Data'),
                              ),
                              TextButton(onPressed: () {}, child: Text('Cancel'))
                            ])),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

如果有任何代码错误,请告诉我。我通过使用setState传递了我的TextForm的值来更改我的标题和描述的当前值,然后期望基于我的标题和描述生成一个列表。

英文:

I am building a note app with details of title and description whereby my input comes from a textfield from an alertDialog popup. Unfortunately, the screen is blank.

This is my UserNotes

class UserNotes{
String? title;
String? descriptioin;
UserNotes({required this.title,required this.descriptioin});
}

This is my provider

import &#39;package:notes_update/models/UserMethods.dart&#39;;
import &#39;package:notes_update/models/UserNotes.dart&#39;;
import &#39;package:flutter/foundation.dart&#39;;
import &#39;package:provider/provider.dart&#39;;
class ProviderData extends ChangeNotifier{
List&lt;UserNotes&gt;_users=[];
List&lt;UserNotes&gt; get newusers=&gt;_users;
IncomingData(){
_users=GettingNotes().addDetails();
notifyListeners();
}
}

This class returns a list of userNotes

import &#39;UserNotes.dart&#39;;
class GettingNotes{
String? newtitle;
String? description;
List&lt;UserNotes&gt; addDetails(){
List&lt;UserNotes&gt;details=[];
if(details.isEmpty){
details.add(UserNotes(title:newtitle!,descriptioin:description! ));
}
return details;
}}

This is my UI

import &#39;package:flutter/cupertino.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:notes_update/models/UserMethods.dart&#39;;
import &#39;package:notes_update/models/UserNotes.dart&#39;;
import &#39;package:provider/provider.dart&#39;;
import &#39;../Provider/Provder.dart&#39;;
class Notes extends StatefulWidget {
createState() =&gt; _Notes();
}
class _Notes extends State&lt;Notes&gt; {
var title;
var description;
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Consumer&lt;ProviderData&gt;(builder:
(BuildContext context, ProviderData value, Widget? child) {
return ListView.builder(
itemCount: value.newusers.length,
itemBuilder: ((context, index) {
return ListTile(
title: Text(value.newusers[index].title!),
leading: Text(value.newusers[index].descriptioin!),
);
}));
}),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
FloatingActionButton(
backgroundColor: Colors.black54,
child: Center(
child: Icon(
Icons.add,
size: 40,
)),
onPressed: () =&gt; showDialog(
context: context,
builder: (BuildContext context) =&gt; AlertDialog(
title: Text(&#39;NOTES INFO&#39;),
content: Column(
children: [
TextFormField(
decoration: InputDecoration(
hintText: &#39;Enter notes title&#39;,
border: OutlineInputBorder()),
onChanged: (value) {
setState(() {
description = value;
});
},
),
SizedBox(height:50),
TextFormField(
decoration: InputDecoration(
hintText: &#39;Enter notes description&#39;,
border: OutlineInputBorder()),
onChanged: (value) {
setState(() {
description = value;
});
},
),
],
),
actions: &lt;Widget&gt;[
TextButton(
onPressed: () {
setState(() {
GettingNotes().newtitle = title;
GettingNotes().description = description;
});
Navigator.pop(context);
},
child: Text(&#39;Save Data&#39;),
),
TextButton(
onPressed: () {}, child: Text(&#39;Cancel&#39;))
])),
),
],
),
],
),
);
}
}

If there is any code mistake, let me know.

I passed on the value of my TextForm using setState to change the current value of my title and description and I expected a list based on my title and description.

答案1

得分: 1

  1. 你在TextFormField中都设置了description的值,但title的值从未设置。

  2. onPressed中,你创建了UserNotes类的新实例,而不是GettingNotes类的实例,并将其添加到ProviderData类中的笔记列表中。

void addNote({
  required String title,
  required String description,
}) {
  _users.add(UserNotes(title: title, description: description));
  notifyListeners();
}

更新后的 UI 代码:

onPressed: () => showDialog(
  context: context,
  builder: (BuildContext context) => AlertDialog(
    title: Text('NOTES INFO'),
    content: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        TextFormField(
          decoration: InputDecoration(
            hintText: '输入笔记标题',
            border: OutlineInputBorder(),
          ),
          onChanged: (value) {
            setState(() {
              title = value; // 在这里设置标题
            });
          },
        ),
        SizedBox(height: 20),
        TextFormField(
          decoration: InputDecoration(
            hintText: '输入笔记描述',
            border: OutlineInputBorder(),
          ),
          onChanged: (value) {
            setState(() {
              description = value;
            });
          },
        ),
      ],
    ),
    actions: <Widget>[
      TextButton(
        onPressed: () {
          if (title != null && description != null) {
            Provider.of<ProviderData>(context, listen: false)
                .newusers
                .add(UserNotes(
                  title: title,
                  description: description,
                ));
            Navigator.pop(context);
          }
        },
        child: Text('保存数据'),
      ),
      TextButton(
        onPressed: () => Navigator.pop(context),
        child: Text('取消'),
      ),
    ],
  ),
)
英文:

Two mistakes:

  1. In both the TextFormField you are setting description value and title value is never set.
  2. In onPressed you are creating new instance of UserNotes class instead of GettingNotes class, and adding it to the list of notes in ProviderData class.

And create a addNote function, where in you add the note to the list.

Updated Provider Code:

  void addNote({
required String title,
required String description,
}) {
_users.add(UserNotes(title: title, descriptioin: description));
notifyListeners();
}
}

Updated UI code:

                onPressed: () =&gt; showDialog(
context: context,
builder: (BuildContext context) =&gt; AlertDialog(
title: Text(&#39;NOTES INFO&#39;),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
decoration: InputDecoration(
hintText: &#39;Enter notes title&#39;,
border: OutlineInputBorder(),
),
onChanged: (value) {
setState(() {
title = value; // &#128072; set title here
});
},
),
SizedBox(height: 20),
TextFormField(
decoration: InputDecoration(
hintText: &#39;Enter notes description&#39;,
border: OutlineInputBorder(),
),
onChanged: (value) {
setState(() {
description = value;
});
},
),
],
),
actions: &lt;Widget&gt;[
TextButton(
onPressed: () {
if (title != null &amp;&amp; description != null) {
Provider.of&lt;ProviderData&gt;(context, listen: false) //&#128072; call it this way
.newusers
.add(UserNotes(
title: title,
description: description,
));  //       
Navigator.pop(context);
}
},
child: Text(&#39;Save Data&#39;),
),
TextButton(
onPressed: () =&gt; Navigator.pop(context),
child: Text(&#39;Cancel&#39;),
),
],

huangapple
  • 本文由 发表于 2023年3月7日 04:58:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定