Sachihiro
Sachihiro

Reputation: 1781

Accessing variables out of scope

I am trying to navigate to a new page newData[index]["title"] when tap on listTile, how can I access newData, index and data variables out of this scope, I know I have to declare them in global scope but I tried this.index, but it doesn't work, I created a _onTap() method but I don't have access to index so I can only access the by asking for a specific position [0] for instance.

class _ContentPageState extends State<ContentPage> {

@override
Widget build(BuildContext context,) {
 List data;
 return new Scaffold(
    appBar: new AppBar(
      title: new Text("Local json file"),
    ),
    body: new Container(
      child: new Center(

        child: new FutureBuilder(
            future: DefaultAssetBundle
                .of(context)
                .loadString('data_files/file.json'),
            builder: (context, snapshot) {
              var newData = JSON.decode(snapshot.data.toString());
              return new ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return new Card(
                    child: new ListTile(
                      title: new Text(newData[index]['title'],textScaleFactor: 1.5),
                    ),
                  );
                },
                itemCount: newData == null ? 0 : newData.length,
              );
            }),
      ),
    ));
   }
 }

Upvotes: 3

Views: 2251

Answers (2)

Mamnarock
Mamnarock

Reputation: 1174

the previous answer is passing newData as argument. Another alternative is declare newData outside the build method.

class _ContentPageState extends State<ContentPage> {

var newData;// << here >> after class

@override
Widget build(BuildContext context,) {

So, in the assign remove de type (var) newData = JSON.decode(snapshot.data.toString());

Upvotes: 0

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277037

I guess you're trying to have a private _onTap method inside your class similar to :

_onTap(newData, int index) {

}

That's pretty simple, inside your ListTile you can wrap your _onTap inside another function like this :

return new Card(
  child: new ListTile(
    onTap: () => _onTap(newData, index),
    title: new Text(newData[index]['title'], textScaleFactor: 1.5),
  ),
);

Upvotes: 3

Related Questions