【问题标题】:Flutter Firebase: not able update DatabaseFlutter Firebase:无法更新数据库
【发布时间】:2020-04-09 15:54:05
【问题描述】:

我想在警报对话框中使用 NumberPicker 更新我的收藏。我在代码或模拟器中没有收到任何错误。当我按下按钮更新代码时,终端不会给出任何错误。一切看起来都很好,但由于某种原因我不工作。当您需要更多信息时,只需留下您所需要的评论即可。 :)

import 'package:flutter/material.dart';
import 'package:numberpicker/numberpicker.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:testapp/services/Services.dart';

import 'models/Goals.dart';

class Statistics extends StatefulWidget {
  @override
  _StatisticsState createState() => _StatisticsState();
}

class _StatisticsState extends State<Statistics> {

  int _currentFirstValue = 1;
  int totalFirst;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: 260,
        child: StreamBuilder(
            stream: FirestoreService().getGoals(),
            builder: (context, AsyncSnapshot<List<Goal>> snapshot) {
              if (snapshot.hasError || !snapshot.hasData) {
                return Center(child: CircularProgressIndicator(
                  backgroundColor: Color(0XFF1954A1),
                ));
              }
              return ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: 1,
                  itemBuilder: (BuildContext context, int index) {
                    // ignore: missing_return
                    Goal goal = snapshot.data[index];
                    return Row(
                      children: <Widget>[
                        Container(
                          padding: EdgeInsets.all(10),
                          margin: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
                          height: 230,
                          width: 350,
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(10.0)),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.grey[300],
                                  offset: const Offset(0.5, 1),
                                  blurRadius: 4.0,
                                  spreadRadius: 0.1,
                                ),
                              ]),
                          child: Column(
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  Text('WeekGoals', style: TextStyle(
                                    fontSize: 25,
                                    fontWeight: FontWeight.w500,
                                  ),),
                                  SizedBox(width: 100),
                                  SizedBox(
                                    height: 20,
                                    width: 87,
                                    child: FlatButton(
                                      child: Text('edit', style: TextStyle(
                                          fontSize: 17,
                                          color: Colors.yellow[700]
                                      ),),
                                      onPressed: () {
                                        return showDialog(
                                            context: context,
                                            barrierDismissible: true,
                                            builder: (context) => AlertDialog(
                                              content: Column(
                                                children: <Widget>[
                                                  Text('weekly goals'),
                                                  NumberPicker.integer(
                                                      initialValue: _currentFirstValue,
                                                      minValue: 1,
                                                      maxValue: 100,
                                                      onChanged: (newGoal) => setState(() => {
                                                        _currentFirstValue = newGoal,
                                                        totalFirst = _currentFirstValue,
                                                      })
                                                  ),
                                                  Row(
                                                    children: <Widget>[
                                                      RaisedButton(
                                                        child: Text('edit goals'),
                                                        onPressed: () async {
                                                          Goal goal = Goal(
                                                            weekActivityGoal: totalFirst,

                                                          );
                                                          await FirestoreService().updateGoal(goal);
                                                          Navigator.pop(context, false);
                                                        },
                                                      ),
                                                      FlatButton(
                                                        child: Text('Close'),
                                                        onPressed: () {
                                                          Navigator.pop(context, false);
                                                        },
                                                      )
                                                    ],
                                                  )
                                                ],
                                              ),
                                            )
                                        );
                                      },
                                    ),
                                  )
                                ],
                              ),
                              SizedBox(height: 10),
                              Row(
                                children: <Widget>[
                                  Container(
                                    padding: EdgeInsets.symmetric(horizontal: 17.5),
                                    child: CircularPercentIndicator(
                                      header: Text('activitys', style: TextStyle(
                                        fontSize: 17,
                                      ),),
                                      radius: 130,
                                      progressColor: Colors.red,
                                      lineWidth: 8,
                                      backgroundColor: Colors.grey[200],
                                      percent: goal.weekActivity*100/goal.weekActivityGoal,
                                      center: Text('${goal.weekActivity}/${goal.weekActivityGoal}'),
                                    ),
                                  ),
                                ],
                              ),

                            ],
                          ),
                        ),
                      ],
                    );
                  });
            }),
      ),
    );
  }
}

【问题讨论】:

  • 请编辑问题,以更清楚地了解哪些方面没有按您预期的方式工作。请务必注意任何错误。我还建议将您的代码缩减为仅失败的部分。
  • @DougStevenson 我编辑了帖子,您需要更多信息吗?

标签: flutter dart google-cloud-firestore


【解决方案1】:

这已经帮助了很多人尝试我也可能对你有帮助。

StreamBuilder(
          stream: Firestore.instance.collection('Hearings').snapshots(),
          builder: (context, snapshot) {
            if (snapshot.hasError) return Text('Error: ${snapshot.error}');
            switch (snapshot.connectionState) {
              case ConnectionState.none:
                return Text('Select lot');
              case ConnectionState.waiting:
                return Text('Awaiting bids...');
              case ConnectionState.active:
                {
                  print('active');
                  return Text('${snapshot.data}');
                }
              case ConnectionState.done:
                {
                  print('Done');
                  return _buildList(context, snapshot.data);
                }
            }
            return null;
          }),
    ));
  }

  Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
   return ListView(
     padding: const EdgeInsets.only(top: 20.0),
     children: snapshot.map((data) => _buildListItem(context, data)).toList(),
   );
 }

 Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
   final record = Record.fromSnapshot(data);

   return Padding(
     key: ValueKey(record.name),
     padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
     child: Container(
       decoration: BoxDecoration(
         border: Border.all(color: Colors.grey),
         borderRadius: BorderRadius.circular(5.0),
       ),
       child: ListTile(
         title: Text(record.name),
         trailing: Text(record.votes.toString()),
         onTap: () => Firestore.instance.runTransaction((transaction) async {
               final freshSnapshot = await transaction.get(record.reference);
               final fresh = Record.fromSnapshot(freshSnapshot);

               await transaction
                   .update(record.reference, {'votes': fresh.votes + 1});
             }),
       ),
     ),
   );
 }
}

class Record {
 final String name;
 final int votes;
 final DocumentReference reference;

 Record.fromMap(Map<String, dynamic> map, {this.reference})
     : assert(map['name'] != null),
       assert(map['votes'] != null),
       name = map['name'],
       votes = map['votes'];

 Record.fromSnapshot(DocumentSnapshot snapshot)
     : this.fromMap(snapshot.data, reference: snapshot.reference);

 @override
 String toString() => "Record<$name:$votes>";

}

这是link此信息的来源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 2020-08-29
    • 2021-10-19
    • 2021-04-15
    • 1970-01-01
    • 2020-12-30
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多