Skip to content

Instantly share code, notes, and snippets.

@hamishnorton
Created August 11, 2022 19:56
Show Gist options
  • Save hamishnorton/b5600ba3a41d8d2f1ede2e2ee65c8da6 to your computer and use it in GitHub Desktop.
Save hamishnorton/b5600ba3a41d8d2f1ede2e2ee65c8da6 to your computer and use it in GitHub Desktop.
Flutter Generic StatefulWidget Example
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Stateful Generic Example';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: _title),
);
}
}
class GenericWidget<T> extends StatefulWidget {
const GenericWidget({Key? key}) : super(key: key);
@override
State<GenericWidget> createState() => _GenericWidgetState<T>();
}
class _GenericWidgetState<T> extends State<GenericWidget<T>> {
@override
Widget build(BuildContext context) {
return Text('type: ${T.toString()}');
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
GenericWidget<String>(),
GenericWidget<int>(),
GenericWidget<bool>(),
GenericWidget<Object>(),
GenericWidget<List<String>>(),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment