Skip to content

Instantly share code, notes, and snippets.

@hectorAguero
Last active March 27, 2021 17:13
Show Gist options
  • Save hectorAguero/faab5bc3c2df9573c0a75a5ce3d4b4b9 to your computer and use it in GitHub Desktop.
Save hectorAguero/faab5bc3c2df9573c0a75a5ce3d4b4b9 to your computer and use it in GitHub Desktop.
Different ways to show or not show null Strings in Text Widgets in Flutter
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String? firtstNullText, secondNullText, thirdNullText;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
firtstNullText = 'now first text is not null';
secondNullText = 'now second text is not null';
thirdNullText = 'now third text is not null';
});
},
child: const Text('Put Text', textAlign: TextAlign.center)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//'Firt Example
//Here if you delete the space after the ??, you can't see the red container
Container(color:Colors.red, child: Text(firtstNullText ?? ' '),),
//Second Example
if (secondNullText != null) Container(color:Colors.blue, child: Text(secondNullText!)),
//Third Example
//The only one you can see before you press the fab button in the bottomRight corner, show 'null' word.
Container(color:Colors.green, child: Text('$thirdNullText')),
]),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment