Как включить / отключить кнопку зависит только от одного текстового поля, используя потоки во флаттере - PullRequest
0 голосов
/ 03 ноября 2019

Я пытаюсь отключить / включить кнопку во флаттере, которая зависит только от одного текстового поля, я использую потоки. Я понятия не имею, как это сделать. Я делал это раньше, но я не могу вспомнить, как я это сделал. вот код.

код TextField:

TextField(
            controller: balanceFieldText,
            onChanged: name == KOREK ? bloc.korekSink : bloc.asiaSink,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              errorText: snapshot.error,
              errorStyle: TextStyle(color: Colors.amber),
              enabledBorder: UnderlineInputBorder(
                borderRadius: BorderRadius.circular(20.5),
              ),
              errorBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.red[900],
                      style: BorderStyle.solid,
                      width: 2)),
              fillColor: Colors.white,
              filled: true,
              prefixIcon: IconButton(
                icon: Icon(
                  Icons.camera_alt,
                  color: Colors.grey,
                ),
                onPressed: () {
                  print('sdfgsg');
                },
              ),
              suffixIcon: IconButton(
                  icon: Icon(
                    Icons.keyboard_voice,
                    color: Colors.grey,
                  ),
                  onPressed: () {
                    print('adfaf');
                  }),
              labelText: 'ژمارەی کارت',
              labelStyle: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.w300,
              ),
              hintText: 'ژمارەی سەر کارتەکە وەك خۆی بنوسەوە',
              hintStyle: TextStyle(color: Colors.grey, fontSize: 12.5),
            ),
          );
        }),

, а вот код моей кнопки:

 RaisedButton(
    child: Text('پڕبکەوە'),
    onPressed: /* how to check it here to make button enable if textfield has no error  */ null,
  );

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

1 Ответ

0 голосов
/ 04 ноября 2019

Я не знаю, что это может решить вашу проблему .... если вы выбираете мое решение, вам нужно обновить pubspec.yaml импортирующую библиотеку rxdart и поставщик . в bloc.dart :

class Bloc extends Object with Validators{
    final Behavior<String> _checkText = Behavior<String>();
    Observable<String> get checkText => _checkText.stream.transform(validateText);// the transform is used to check whenever there is some changed in your textfield and done some validation 
    Function(String) get checkTextOnChanged => _checkText.sink.add;
}

в validators.dart:

class Validators {
  final StreamTransformer<String, String> validateText =
      StreamTransformer<String, String>.fromHandlers(
          handleData: (String text, EventSink<String> sink) {

    // Sample of checking text pattern 
    const Pattern pattern = r'^[0-9]*$';
    final RegExp regex = RegExp(pattern);

    if (text != null) {
      if (!regex.hasMatch(text)) {
        sink.add(null);
        sink.addError('text only accept number!');
      } else {
        sink.add(text);
      }
    }
  });
}

в вашем screen.dart:

final Bloc bloc = Provider.of<Bloc>();
TextField(
    .....
    onChanged: bloc.checkText,
    .....
);

StreamBuilder(
    stream:bloc.checkText, 
    builder:(BuildContext context, AsyncSnapshot<String> snapshot){
    return RaisedButton(
        .....
        onPressed: !snapshot.hasdata ? null : buttonOnPressedEvent(), // handle event when the textfield is valid or not
        color: !snapshot.hasdata ? Colors.grey : Colors.blue // this used to change preview color button if the data has exist
        .....
    );
});

Надеюсь, что это может дать вам некоторое вдохновение, как решить вашу проблему, удачи!

...