I have a problem with displaying the string output in Flutter App, I wanted to display the string value in column like this:
I
want
to
split
this
but instead I got this output:
[I, want, to, split, this]
I don't know what to do anymore as I am still new to programming, but I think this code below must be the cause:
void _splitWordInColumn(){
setState(() {
sentenceToWord.forEach((e) => print(e));
});
}
This is the image of that wrong output and below is my full code:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> sentenceToWord = 'I want to split this'.split(" ");
void _splitWordInColumn(){
setState(() {
sentenceToWord.forEach((e) => print(e));
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo HomePage'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(sentenceToWord.toString()),
],
),
),
);
}
}
I hope someone can help me fix this, Thank you.
CodePudding user response:
Try to use map
operator with the column
.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: sentenceToWord.map((e) => Text(e)).toList(),
),
CodePudding user response:
Try this :
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String sentenceToWord = 'I \nwant \nto \nsplit \nthis';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo HomePage'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(sentenceToWord),
],
),
),
);
}
}