Как я могу сделать динамический контроллер с флаттером слушателя

#flutter #dart #controller #listener

Вопрос:

я новичок в Flutter , и я хочу сделать этот _billAmountController динамическим с помощью кнопки

когда я пытался это сделать , он просто дублировал его текстовое поле, но всякий раз, когда я изменяю число внутри любого из полей, число меняется во всех из них (потому что это один и тот же контроллер).

, так что не могли бы вы , пожалуйста, помочь мне понять, как сделать динамический, чтобы всякий раз, когда я нажимаю кнопку добавить, он создавал новое текстовое поле, но с динамическим контроллером, чтобы оно не влияло на другие ?

Спасибо

вот простая часть кода

 
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(TipCalculatorApp());
}

class TipCalculatorApp extends StatefulWidget {
  @override
  _TipCalculatorAppState createState() => _TipCalculatorAppState();
}

class _TipCalculatorAppState extends State<TipCalculatorApp> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(new FocusNode());
        },
        child: MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Bill',
          theme: ThemeData(primaryColor: Colors.green),
          home: TipCalculatorPage(),
        ));
  }
}

class TipCalculatorPage extends StatefulWidget {
  @override
  _TipCalculatorPageState createState() => _TipCalculatorPageState();
}

class _TipCalculatorPageState extends State<TipCalculatorPage> {
  static const defaultBillAmount = 0;

  final _billAmountController =
      TextEditingController(text: defaultBillAmount.toString());

  int _billAmount = defaultBillAmount;

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

    _billAmountController.addListener(_onBillAmountChanged);
  }

  _onBillAmountChanged() {
    setState(() {
      _billAmount = int.tryParse(_billAmountController.text) ?? 0;
    });
  }

  _getTotalAmount() => _billAmount;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Center(
              child:
                  Row(mainAxisAlignment: MainAxisAlignment.center, children: [
        Text(
          'Total',
          style: TextStyle(
            color: Colors.black,
          ),
        ),
      ]))),
      body: Column(
        children: [
          TextFormField(
            key: Key("billAmount"),
            controller: _billAmountController,
            keyboardType: TextInputType.phone,
            decoration: InputDecoration(
              labelStyle: TextStyle(
                  fontSize: 25, letterSpacing: 0, fontWeight: FontWeight.bold),
              fillColor: Colors.white,
              border: new OutlineInputBorder(
                borderRadius: new BorderRadius.circular(20.0),
                borderSide: new BorderSide(),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.all(15),
            padding: EdgeInsets.all(15),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(
                Radius.circular(15),
              ),
              border: Border.all(color: Colors.white),
              boxShadow: [
                BoxShadow(
                  color: Colors.blueAccent,
                  offset: Offset(0, 1),
                  spreadRadius: 1,
                  blurRadius: 12,
                ),
              ],
            ),
            child: Flexible(
              child: Column(
                children: [
                  AmountText(
                    'Total: ${_getTotalAmount()}',
                    key: Key('totalAmount'),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

class AmountText extends StatelessWidget {
  final String text;

  const AmountText(
    this.text, {
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 10.0, right: 10),
      child: Text(text.toUpperCase(),
          style: TextStyle(
              fontWeight: FontWeight.bold, color: Colors.red, fontSize: 20)),
    );
  }
}


 
 

Комментарии:

1. привет? может кто-нибудь помочь