import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: StreamFlutter(),
),
);
}
class StreamFlutter extends StatefulWidget {
const StreamFlutter({super.key});
@override
State<StreamFlutter> createState() => _StreamFlutterState();
}
class _StreamFlutterState extends State<StreamFlutter> {
final TextEditingController textEditingController = TextEditingController();
final List<String> languages = []; // Use String type for languages
final StreamController<List<String>> streamController = StreamController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Languages'),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5),
child: Column(
children: [
Row(
// Use Row for horizontal layout of text field and button
children: [
Expanded(
child: TextFormField(
controller: textEditingController,
),
),
const SizedBox(width: 10),
ElevatedButton(
onPressed: () {
final input = textEditingController.text;
languages.add(input);
streamController.sink.add(languages); // Emit updated list
textEditingController.clear();
},
child: const Text('Add Language'),
),
],
),
Expanded(
child: Container(
color: Colors.green,
child: StreamBuilder<List<String>>(
// Use generic type for clarity
stream: streamController.stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(snapshot.data![index]),
),
);
},
);
} else {
return const Text(
'No languages added yet'); // Informative message
}
},
),
),
),
],
),
),
);
}
@override
void dispose() {
streamController.close(); // Close the stream when widget is disposed
super.dispose();
}
}
class StreamFlutter2 extends StatefulWidget {
const StreamFlutter2({super.key});
@override
State<StreamFlutter2> createState() => _StreamFlutter2State();
}
class _StreamFlutter2State extends State<StreamFlutter2> {
int counter = 0;
final StreamController<int> streamController = StreamController();
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
counter++;
streamController.sink.add(counter);
},
child: const Icon(Icons.add),
),
body: SafeArea(
child: Center(
child: StreamBuilder<int>(
// Use generic type for clarity
stream: streamController.stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.toString());
} else {
return const Text('0'); // Informative default value
}
},
),
),
),
);
}
@override
void dispose() {
streamController.close(); // Close the stream when widget is disposed
super.dispose();
}
}