简体   繁体   中英

How can I use Flutter bloc to build a text field that updates its value to another widget as the user types?

I am looking for something close to what you have on Google fonts. https://fonts.google.com/

I create a sample demo which work like that

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

void main() {
  // for bloc transition trace
  //BlocSupervisor.delegate = SimpleBlocDelegate();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<TextUpdateBloc>(
      create: (context) => TextUpdateBloc(),
      child: MaterialApp(
        home: Scaffold(body: DeleteWidget()),
      ),
    );
  }
}

class TextInputState {}

class TextInputInitState extends TextInputState {
  String text;
  TextInputInitState({this.text});
}

class TextInputDataChange extends TextInputState {
  String text;
  TextInputDataChange({this.text});
}

class TextEvents {}

class TextInit extends TextEvents {}

class TextChange extends TextEvents {
  final String data;
  TextChange({@required this.data});
}

class TextUpdateBloc extends Bloc<TextEvents, TextInputState> {
  @override
  get initialState => TextInputInitState(text: "");

  @override
  Stream<TextInputState> mapEventToState(event) async* {
    if (event is TextInit) {
      yield TextInputInitState(text: "");
    } else if (event is TextChange) {
      yield TextInputInitState(text: event.data);
    }
  }
}

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

  @override
  Widget build(BuildContext context) {
    final TextUpdateBloc counterBloc = BlocProvider.of<TextUpdateBloc>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('test app'),
      ),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            TextFormField(
              onChanged: (value) => counterBloc.add(TextChange(data: value)),
            ),
            Container(
              child: BlocBuilder<TextUpdateBloc, TextInputState>(
                builder: (context, state) {
                  if (state is TextInputInitState) {
                    return Text(state.text.toString());
                  } else if (state is TextInputDataChange) {
                    return Text(state.text.toString());
                  } else {
                    return Text("something worng");
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM