如果点击键盘上的"完成"按钮,则无法运行Flutter Hive putAt()

ars1skjm  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(195)

我尝试使用hive作为数据库来制作一个flutter应用程序。有一个显示余额的容器,如果用户单击该容器,将显示一个表单对话框来更改余额值。更改TextFormField上的值后,如果用户单击提交,一切都会正常工作,但如果用户在单击提交按钮之前单击键盘上的完成按钮,该值将不会更改。但如果用户再次单击容器并单击TextFormField,则值会突然更改。
如果我在TextFormField onFieldSubmitted中添加hive putAt方法,则当用户单击“完成”按钮时,该值将更改,但我希望该值在用户单击“提交”按钮而不是“完成”按钮时更改。
GitHub Code
main.dart

import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive_test/model/balance.dart';
import 'package:hive_test/ui/pages/main_page.dart';

Future<void> main() async {
  await Hive.initFlutter();
  Hive.registerAdapter(BalanceAdapter());
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainPage(),
    );
  }
}

balance.dart

import 'package:hive/hive.dart';

part 'balance.g.dart';

@HiveType(typeId: 1)
class Balance {
  Balance({required this.value});
  @HiveField(0)
  int value;
}

balance.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'balance.dart';

// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************

class BalanceAdapter extends TypeAdapter<Balance> {
  @override
  final int typeId = 1;

  @override
  Balance read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return Balance(
      value: fields[0] as int,
    );
  }

  @override
  void write(BinaryWriter writer, Balance obj) {
    writer
      ..writeByte(1)
      ..writeByte(0)
      ..write(obj.value);
  }

  @override
  int get hashCode => typeId.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is BalanceAdapter &&
          runtimeType == other.runtimeType &&
          typeId == other.typeId;
}

主页.dart

import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive_test/model/balance.dart';

class MainPage extends StatelessWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double maxWidth = MediaQuery.of(context).size.width;

    Widget balance(balanceModel) {
      var balanceValue = balanceModel.getAt(0);
      TextEditingController balanceController =
          TextEditingController(text: balanceValue.value.toString());

      return ValueListenableBuilder(
        valueListenable: Hive.box('balance').listenable(),
        builder: (context, box, widget) {
          return Align(
            alignment: Alignment.topCenter,
            child: Container(
              margin: const EdgeInsets.only(top: 10),
              child: ElevatedButton(
                onPressed: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        scrollable: true,
                        title: Container(
                          alignment: Alignment.center,
                          child: Text('Jumlah'),
                        ),
                        content: Padding(
                          padding: const EdgeInsets.all(5.0),
                          child: Form(
                            child: TextFormField(
                              controller: balanceController,
                              decoration: InputDecoration(
                                labelText: 'Saldo',
                                icon: Icon(Icons.money_sharp),
                              ),
                              keyboardType: TextInputType.number,
                            ),
                          ),
                        ),
                        actions: [
                          ElevatedButton(
                            child: Text("Submit"),
                            onPressed: () {
                              balanceModel.putAt(
                                0,
                                Balance(
                                  value: int.parse(balanceController.text),
                                ),
                              );
                              Navigator.pop(context);
                            },
                            style: ElevatedButton.styleFrom(
                              fixedSize: Size(maxWidth * 9 / 10, 50),
                            ),
                          ),
                        ],
                      );
                    },
                  );
                },
                child: Text(
                  'Balance: ${balanceValue.value.toString()}',
                ),
                style: ElevatedButton.styleFrom(
                  fixedSize: Size(maxWidth * 9 / 10, 50),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(14),
                  ),
                ),
              ),
            ),
          );
        },
      );
    }

    return Scaffold(
      appBar: AppBar(),
      body: FutureBuilder(
        future: Hive.openBox('balance'),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Center(
                child: Text(
                  snapshot.error.toString(),
                ),
              );
            } else {
              var balanceModel = Hive.box('balance');
              if (balanceModel.length == 0) {
                balanceModel.add(Balance(value: 0));
              }

              return balance(balanceModel);
            }
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}

完成按钮

vuktfyat

vuktfyat1#

键盘submit是使用TextFormField中的onSubmit方法属性触发的,因此不是调用ElevatedButtononPressed属性中的Hive.puAt()
您需要将GlobalKey分配给TextFomrField,然后从ElevatedButton提交

相关问题